tags:
- code
topic: Maths
difficulty: Easy
link: https://www.codewars.com/kata/5a3fe3dde1ce0e8ed6000097/solutions/python
date: 2023-10-21Problem
Given a year, return the century it is in. Note that the year should be interpreted via strict construction (as in the 19th century spans from the years 1901-2000) rather than popular perception (the 19th century spans from the years 1900-1999).
century(1601) # Returns 17
century(356) # Returns 4
century(89) # Returns 1
def century(year):
return (year+99)//100
from math import ceil
def century(year):
return ceil(year / 100)
//, also known as floor division - this rounds the result down to the nearest whole number.
// instead rounds down to 19 which is correct according to the strict definition.2000 - in which case, the century is 20. For every other year in that same century (19xx), however, the century would be xx+1.
xx01 and end at (xx+1)00. Say that the year was 2000. Adding 99 makes it equal to 2099, whereas adding 100 makes it equal to 2100. We note that 2099/100 = 20, while 2100/100 = 21, the latter of which is incorrect.ceil(foo) returns the foo rounded up to the nearest integer, if not already an integer. This works because our special cases (xx00) divided by 100 are still integers, so nothing happens to them.